﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Net;
using System.Xml.Linq;
using System.Drawing;

namespace SPThumbnailExtender.Interne
{
    internal class ThumbnailWord : ThumbnailBase
    {
        public ThumbnailWord(Uri uri)
            : base(uri)
        {
            this.Width = 420;
            this.Height = 594;
        }
        public ThumbnailWord(Uri uri, int Width, int Height)
            : base(uri, Width, Height)
        { }
        public override System.Drawing.Bitmap GenerateThumbnail()
        {
            return GenerateThumbnail(0);
        }

        public override System.Drawing.Bitmap GenerateThumbnail(int Page)
        {
            string strWebUrl;
            string strDoc;
            using (SPSite siteCollection = new SPSite(this.FileUri.AbsoluteUri))
            {
                using (SPWeb myWeb = siteCollection.OpenWeb())
                {
                    strWebUrl = myWeb.Url;
                    strDoc = this.FileUri.AbsoluteUri.Replace(siteCollection.Url, "");
                }
            }

            string extension = Path.GetExtension(this.FileUri.AbsoluteUri).ToLower();

            string infoUrl = strWebUrl + "/_layouts/MobileDocHandler.ashx?doc=" + strDoc;

            if (extension == ".doc")
                infoUrl += "&type=thumbnail";

            Uri uri = new Uri(infoUrl, UriKind.Absolute);

            Bitmap bmpToWrite = null;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            {
                string resultString = streamReader.ReadToEnd();
                XDocument xdoc = XDocument.Parse(resultString);
                string strUrlImage = xdoc.Element("mobileDoc").Element("pageImage").Attribute("url").Value;
                string strUrlDocXml = xdoc.Element("mobileDoc").Element("pageXml").Attribute("url").Value;

                string dimension = string.Format("&width={0}&height={1}", this.Width, this.Height);
                string thumbnailUrl;
                if (extension == ".doc")
                {
                    thumbnailUrl = strWebUrl + "/_layouts/" + strUrlImage + "&n=t1.jpg" + dimension;
                }
                else
                {
                    int iPageEnd = ((Page / 10)+1) * 10 ;
                    int iPageStart = iPageEnd -9 ;
                    string firstPageID="0";
                    HttpWebRequest requestDocXML = (HttpWebRequest)HttpWebRequest.Create(strWebUrl + "/_layouts/" + strUrlDocXml + "&n=p_1_10.xml");
                    requestDocXML.Credentials = CredentialCache.DefaultCredentials;
                    HttpWebResponse responseDocXML = (HttpWebResponse)requestDocXML.GetResponse();
                    using (StreamReader streamReaderDocXml = new StreamReader(responseDocXML.GetResponseStream()))
                    {
                        string resultStringDocXml = streamReaderDocXml.ReadToEnd();
                        XDocument xdocxml = XDocument.Parse(resultStringDocXml);
                        firstPageID = xdocxml.Element("Pages").Element("Page").Element("P").Element("L").Element("LT").Attribute("p").Value;
                    }
                    int iFirstPageID=int.Parse(firstPageID);
                    
                    requestDocXML = (HttpWebRequest)HttpWebRequest.Create(strWebUrl + "/_layouts/" + strUrlDocXml + "&n=p_"+  iPageStart +"_"  + iPageEnd + ".xml");
                    requestDocXML.Credentials = CredentialCache.DefaultCredentials;
                    responseDocXML = (HttpWebResponse)requestDocXML.GetResponse();
                    using (StreamReader streamReaderDocXml = new StreamReader(responseDocXML.GetResponseStream()))
                    {
                        string resultStringDocXml = streamReaderDocXml.ReadToEnd();
                        XDocument xdocxml = XDocument.Parse(resultStringDocXml);
                        thumbnailUrl = strWebUrl + "/_layouts/" + strUrlImage + "&n=p" + (Page + iFirstPageID).ToString() + ".img" + dimension;
                    }
                }
                Uri imageUrl = new Uri(thumbnailUrl);
                Helper.GetBitmapFromUri(imageUrl, out bmpToWrite);
                Helper.DeleteThumbnail(this.FileUri, Page );
                Helper.InsertThumbnail(this.FileUri, Page, bmpToWrite);
            }
            return bmpToWrite;
        }

        public override int GetCount()
        {
            string strWebUrl;
            string strDoc;
            int iFirstPage = 0;
            using (SPSite siteCollection = new SPSite(this.FileUri.AbsoluteUri))
            {
                using (SPWeb myWeb = siteCollection.OpenWeb())
                {
                    strWebUrl = myWeb.Url;
                    strDoc = this.FileUri.AbsoluteUri.Replace(siteCollection.Url, "");
                }
            }

            string extension = Path.GetExtension(this.FileUri.AbsoluteUri).ToLower();

            if (extension == ".doc")
                return 1;

            string infoUrl = strWebUrl + "/_layouts/MobileDocHandler.ashx?doc=" + strDoc;


            Uri uri = new Uri(infoUrl, UriKind.Absolute);

            int pageCount = 0;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            {
                string resultString = streamReader.ReadToEnd();
                XDocument xdoc = XDocument.Parse(resultString);
                string strUrlDocXml = xdoc.Element("mobileDoc").Element("pageXml").Attribute("url").Value;
                if (extension == ".doc")
                    pageCount = int.Parse(xdoc.Element("mobileDoc").Element("docdata").Element("document").Element("pageset").Attribute("count").Value);
                else
                    pageCount = int.Parse(xdoc.Element("mobileDoc").Element("document").Element("pageset").Attribute("count").Value);
                string firstPageID = "0";
                HttpWebRequest requestDocXML = (HttpWebRequest)HttpWebRequest.Create(strWebUrl + "/_layouts/" + strUrlDocXml + "&n=p_1_10.xml");
                requestDocXML.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse responseDocXML = (HttpWebResponse)requestDocXML.GetResponse();
                using (StreamReader streamReaderDocXml = new StreamReader(responseDocXML.GetResponseStream()))
                {
                    string resultStringDocXml = streamReaderDocXml.ReadToEnd();
                    XDocument xdocxml = XDocument.Parse(resultStringDocXml);
                    firstPageID = xdocxml.Element("Pages").Element("Page").Element("P").Element("L").Element("LT").Attribute("p").Value;
                }
                iFirstPage = int.Parse(firstPageID);
            }
            return pageCount - iFirstPage;
        }


        public override void GenerateThumbnails()
        {
            int iPageCount = GetCount();
            Helper.DeleteThumbnailsForDocument(this.FileUri);
            object o = Helper.GetParameter("SPThumbnailExtender.NbPage");
            int iNBPage;
            if(o==null)
                iNBPage=0;
            else
                int.TryParse(o.ToString(), out iNBPage);
            
            for (int miind = 0; miind < iPageCount; miind++)
            {
                if (iNBPage > 0 && miind > iNBPage)
                {
                    break;
                }

                GenerateThumbnail(miind);
            }
        }
    }
}
